package site.sorghum.ddl.defaults;

import java.math.BigDecimal;
import java.sql.JDBCType;
import java.time.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Java类型与JDBC类型转换器
 * 功能：提供Java数据类型与JDBC数据类型之间的转换能力
 */
public class JavaTypeToJdbcTypeConverter {
    private static final Map<Class<?>, JDBCType> TYPE_MAPPINGS = new HashMap<>();

    static {
        // Primitive types
        TYPE_MAPPINGS.put(boolean.class, JDBCType.BOOLEAN);
        TYPE_MAPPINGS.put(byte.class, JDBCType.TINYINT);
        TYPE_MAPPINGS.put(short.class, JDBCType.SMALLINT);
        TYPE_MAPPINGS.put(int.class, JDBCType.INTEGER);
        TYPE_MAPPINGS.put(long.class, JDBCType.BIGINT);
        TYPE_MAPPINGS.put(float.class, JDBCType.FLOAT);
        TYPE_MAPPINGS.put(double.class, JDBCType.DOUBLE);

        // Wrapper types
        TYPE_MAPPINGS.put(Boolean.class, JDBCType.BOOLEAN);
        TYPE_MAPPINGS.put(Byte.class, JDBCType.TINYINT);
        TYPE_MAPPINGS.put(Short.class, JDBCType.SMALLINT);
        TYPE_MAPPINGS.put(Integer.class, JDBCType.INTEGER);
        TYPE_MAPPINGS.put(Long.class, JDBCType.BIGINT);
        TYPE_MAPPINGS.put(Float.class, JDBCType.FLOAT);
        TYPE_MAPPINGS.put(Double.class, JDBCType.DOUBLE);
        TYPE_MAPPINGS.put(BigDecimal.class, JDBCType.DECIMAL);

        // String types
        TYPE_MAPPINGS.put(String.class, JDBCType.VARCHAR);
        TYPE_MAPPINGS.put(Character.class, JDBCType.CHAR);
        TYPE_MAPPINGS.put(char.class, JDBCType.CHAR);

        // Date/time types
        TYPE_MAPPINGS.put(Date.class, JDBCType.TIMESTAMP);
        TYPE_MAPPINGS.put(java.sql.Date.class, JDBCType.DATE);
        TYPE_MAPPINGS.put(java.sql.Time.class, JDBCType.TIME);
        TYPE_MAPPINGS.put(java.sql.Timestamp.class, JDBCType.TIMESTAMP);
        TYPE_MAPPINGS.put(LocalDate.class, JDBCType.DATE);
        TYPE_MAPPINGS.put(LocalTime.class, JDBCType.TIME);
        TYPE_MAPPINGS.put(LocalDateTime.class, JDBCType.TIMESTAMP);
        TYPE_MAPPINGS.put(OffsetDateTime.class, JDBCType.TIMESTAMP_WITH_TIMEZONE);
        TYPE_MAPPINGS.put(ZonedDateTime.class, JDBCType.TIMESTAMP_WITH_TIMEZONE);

        // Binary types
        TYPE_MAPPINGS.put(byte[].class, JDBCType.VARBINARY);
    }

    /**
     * 根据Java类型获取对应的JDBC类型
     *
     * @param javaType 输入的Java类型，不可为null
     * @return 对应的JDBCType枚举值
     * @throws IllegalArgumentException 当输入为null或找不到对应映射时抛出
     */
    public static JDBCType getJdbcType(Class<?> javaType) {
        if (javaType == null) {
            throw new IllegalArgumentException("Java type cannot be null");
        }

        JDBCType jdbcType = TYPE_MAPPINGS.get(javaType);
        if (jdbcType == null) {
            return defaultType(javaType);
        }
        return jdbcType;
    }

    public static JDBCType defaultType(Class<?> javaType) {
        return JDBCType.VARCHAR;
    }
}
